<script setup lang="ts" name="B29PiniaLoveTalk">
import { ref } from "vue";
import { useLoveTalkStore } from "../../store/loveTalk.ts";
import { storeToRefs } from "pinia";

const loveTalkStore = useLoveTalkStore();
const { talkList } = storeToRefs(loveTalkStore);

// 订阅
loveTalkStore.$subscribe((_mutation, state) => {
  localStorage.setItem("TALK_LIST", JSON.stringify(state.talkList));
});

const isLoading = ref<boolean>(false);

const getTalk = async () => {
  try {
    isLoading.value = true;
    loveTalkStore.addTalk();
  } catch (e) {
    window.alert((e as Error).message);
    console.log(e);
  } finally {
    isLoading.value = false;
  }
};
</script>

<template>
  <div class="bg-orange-100 p-3 shadow rounded flex flex-col gap-y-3">
    <div>
      <button class="px-1 py-0.5 border bg-blue-100 disabled:bg-gray-100" :disabled="isLoading" @click="getTalk">
        获取一句土味情话
      </button>
    </div>
    <ul>
      <li v-for="talk in talkList" :key="talk.id" class="my-2 px-1 py-0.5 even:bg-gray-50">
        {{ talk.title }}
      </li>
      <li v-if="!(talkList && talkList.length > 0)" class="italic">
        暂时木有情话
      </li>
    </ul>
  </div>
</template>
